package com.jack.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * JSONP 处理
 * @author LiJiakui
 * @date 17/6/12
 */
public class AccessFilter extends ZuulFilter{
    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        try {
            RequestContext ctx = RequestContext.getCurrentContext();
            HttpServletRequest request = ctx.getRequest();
            Object callback = request.getParameter("callback");
            if(!StringUtils.isEmpty(callback)){
                InputStream stream = ctx.getResponseDataStream();
                String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
                ctx.setResponseBody(callback+"("+body+")");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
